package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("AdulterlinkService")
@Transactional

public class AdulterlinkServiceImpl extends CmiEmaService implements AdulterlinkService {
	public AdulterlinkServiceImpl() {
	}

	@Transactional
	public Adulterlink saveAdulterlink(Adulterlink adulterlink) {
		Set<Eventadulterlink> existingEventadulterlinksForAdulterlink = new HashSet<Eventadulterlink>();

		Set<Eventadulterlink> selectedEventadulterlinksForAdulterlink = adulterlink
				.getEventadulterlinksForAdulterlink();

		if (adulterlink.getId() == null) {

			Adulterlink existingAdulterlink = adulterlinkDAO.findAdulterlinkByPhysicalPrimaryKey(adulterlink.getName());

			if (isEquals(adulterlink, existingAdulterlink)) {
				return existingAdulterlink;
			}

			adulterlink = adulterlinkDAO.store(adulterlink);
			adulterlinkDAO.flush();

			for (Eventadulterlink relatedEventadulterlink : selectedEventadulterlinksForAdulterlink) {
				relatedEventadulterlink.setAdulterlink(adulterlink);
				eventadulterlinkDAO.store(relatedEventadulterlink);
			}
		} else {
			Adulterlink existingAdulterlink = adulterlinkDAO.findAdulterlinkByPrimaryKey(adulterlink.getId());

			existingEventadulterlinksForAdulterlink = existingAdulterlink.getEventadulterlinksForAdulterlink();

			Set<Eventadulterlink> prepareDeleteEventadulterlinksForAdulterlink = new HashSet<Eventadulterlink>();
			Set<Eventadulterlink> prepareAddEventadulterlinksForAdulterlink = new HashSet<Eventadulterlink>();

			prepareDeleteEventadulterlinksForAdulterlink.addAll(selectedEventadulterlinksForAdulterlink);
			prepareDeleteEventadulterlinksForAdulterlink.addAll(existingEventadulterlinksForAdulterlink);

			prepareAddEventadulterlinksForAdulterlink.addAll(selectedEventadulterlinksForAdulterlink);
			prepareAddEventadulterlinksForAdulterlink.addAll(existingEventadulterlinksForAdulterlink);

			prepareDeleteEventadulterlinksForAdulterlink.removeAll(selectedEventadulterlinksForAdulterlink);
			prepareAddEventadulterlinksForAdulterlink.removeAll(existingEventadulterlinksForAdulterlink);

			for (Eventadulterlink relatedEventadulterlink : prepareAddEventadulterlinksForAdulterlink) {
				relatedEventadulterlink.setAdulterlink(adulterlink);
				eventadulterlinkDAO.store(relatedEventadulterlink);
			}

			for (Eventadulterlink relatedEventadulterlink : prepareDeleteEventadulterlinksForAdulterlink) {
				relatedEventadulterlink.setAdulterlink(null);
				eventadulterlinkDAO.store(relatedEventadulterlink);
			}
			adulterlink = adulterlinkDAO.store(adulterlink);
			adulterlinkDAO.flush();
		}

		eventadulterlinkDAO.flush();
		return adulterlink;
	}

	public void deleteAdulterlink(Adulterlink adulterlink) {
		adulterlinkDAO.remove(adulterlink);
		adulterlinkDAO.flush();
	}

	@Transactional
	public void deleteAdulterlinks(Set<Integer> deleteAdulterlinksId) {
		Query query = adulterlinkDAO.createNamedQuery("deleteAdulterlinksById", -1, -1);
		query.setParameter(1, deleteAdulterlinksId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Adulterlink> loadAdulterlinks() {
		return adulterlinkDAO.findAllAdulterlinks();

	}

	@Transactional
	public Set<Adulterlink> loadReferenceAdulterlinks(Set<Adulterlink> adulterlinks) {
		Iterator<Adulterlink> adulterlinksIterator = adulterlinks.iterator();
		Set<Adulterlink> referencedAdulterlinks = new HashSet<>();
		while (adulterlinksIterator.hasNext()) {
			Adulterlink currentAdulterlink = adulterlinksIterator.next();

			if (!currentAdulterlink.getEventadulterlinksForAdulterlink().isEmpty()) {
				referencedAdulterlinks.add(currentAdulterlink);
				continue;
			}
		}
		return referencedAdulterlinks;
	}

	public Set<Adulterlink> loadAdulterlinksByIdSet(Set<Integer> adulterlinkIdSet) {

		Iterator<Integer> adulterlinkIdIterator = adulterlinkIdSet.iterator();
		Set<Adulterlink> adulterlinkSet = new HashSet<>();
		while (adulterlinkIdIterator.hasNext()) {
			Integer id = adulterlinkIdIterator.next();
			Adulterlink currentAdulterlink = adulterlinkDAO.findAdulterlinkById(id);
			adulterlinkSet.add(currentAdulterlink);
		}
		return adulterlinkSet;
	}

	@Transactional
	public List<Adulterlink> findAllAdulterlinks(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Adulterlink>(adulterlinkDAO.findAllAdulterlinks(startResult, maxRows));
	}

	@Transactional
	public Adulterlink findAdulterlinkByPrimaryKey(Integer id) {
		return adulterlinkDAO.findAdulterlinkByPrimaryKey(id);
	}

	@Transactional
	public Integer countAdulterlinks() {
		return ((Long) adulterlinkDAO.createQuerySingleResult("select count(o) from Adulterlink o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countAdulterlinks(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Adulterlink.class);
		return ((Long) adulterlinkDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countAdulterlinksByName(String queryName) {
		Query query = adulterlinkDAO.createNamedQuery("countAdulterlinksByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countAdulterlinksByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Adulterlink.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadAdulterlinkObjectReferencedSet(Adulterlink adulterlink) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> eventadulterlinksIds = new HashSet<Integer>();
		for (Eventadulterlink obj : adulterlink.getEventadulterlinksForAdulterlink()) {

			eventadulterlinksIds.add(obj.getId());
		}
		objectReferencedSetMap.put("eventadulterlinksIds", eventadulterlinksIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadAdulterlinkClassReferencedSet(Adulterlink adulterlink) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("eventadulterlinks", eventadulterlinkDAO.findAllEventadulterlinks());

		return classReferencedSetMap;
	}

	public boolean isEquals(Adulterlink adulterlink, Object obj) {
		if (obj == adulterlink)
			return true;
		if (!(obj instanceof Adulterlink))
			return false;
		Adulterlink comparedAdulterlink = (Adulterlink) obj;
		if (!CheckPropertyEqual(adulterlink.getName(), comparedAdulterlink.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

